package com.example.demo.controller;

import com.example.demo.domain.User;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

@Controller
public class LoginController
{
    @Value("${ip}")
    private String ip;
    @Value("${server.port}")
    private String port;
    @Value("${uploadGoodsPath}")
    private String uploadGoodsPath;
    @Value("${uploadIconPath}")
    private String uploadIconPath;
    @Value("${goodsPicPathPattern}")
    private String goodsPicPathPattern;
    @Value("${iconPathPattern}")
    private String iconPathPattern;
    @Resource
    private UserService userService;
    /**
     * @Create:     Space
     * @Time:       2020-06-10 16:52:00
     * @Describe:   登录
     */
    @RequestMapping("/userLogin")
    public String Login(@RequestParam(name="username",required = false)String username, @RequestParam(name="password",required = false)String password,
                        RedirectAttributes model, HttpServletRequest request, @RequestParam(name="path",required = false)String path)
    {
        request.getSession().setAttribute("goodsPicPath", "http://"+ip+":"+port+goodsPicPathPattern);
        request.getSession().setAttribute("iconPathPattern", "http://"+ip+":"+port+iconPathPattern);
        if(userService.CheckPassword(username,password))
        {

            request.getSession().setAttribute("user",userService.getUserByUserName(username));
            model.addFlashAttribute("loginMsg", "");
            return "redirect:"+path;
        }
        else
        {
            model.addFlashAttribute("loginMsg", "用户名或密码错误");
            return "redirect:"+path;
        }
    }

    @RequestMapping("/logOut")
    public String Logout(HttpServletRequest request)
    {
        request.getSession().removeAttribute("user");
        return "redirect:/";
    }
}
